<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Resize.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instruction_Resize extends Zimm_Model_DbTable_Instruction_Abstract
{
    /**
     * Simple resize to new width and height.
     *
     * @param resource $image GD resource
     * @param string $savePath Target save path
     * @param array $params Instruction arguments
     * @return boolean Indicates if image was altered
     */
    protected function _process(&$image, $savePath, $params)
    {
        $toWidth = isset($params['width']) ? $params['width'] : NULL;
        $toHeight = isset($params['height']) ? $params['height'] : NULL;
        if ($toWidth || $toHeigt) {
            $fromWidth = imagesx($image);
            $fromHeight = imagesy($image);
            if (strpos($toWidth, '%')) {
                $toWidth = (int)(0.01 * $fromWidth * (float)$toWidth);
            }

            if (strpos($toHeight, '%')) {
                $toHeight = (int)(0.01 * $fromHeight * (float)$toHeight);
            }

            if (!$toWidth && $toHeight) {
                $toWidth = (int)($fromWidth * ($toHeight / $fromHeight));
            } else if (!$toHeight && $toWidth) {
                $toHeight = (int)($fromHeight * ($toWidth / $fromWidth));
            }

            if ($toWidth && $toHeight) {
                $im_dest = imagecreatetruecolor($toWidth, $toHeight);
                imagealphablending($im_dest, false);
                imagecopyresampled($im_dest, $image, 0, 0, 0, 0, $toWidth, $toHeight, $fromWidth, $fromHeight);
                imagedestroy($image);
                $image = $im_dest;
                return true;
            }
        }
        return false;
    }
}